import { defineStore } from 'pinia'
import router from '@/router'
import { menuToRoutes } from '@/utils/menuToRoute'

export const useMenuStore = defineStore('menu', {
  state: () => ({
    menuList: [] as any[],
    menuLoaded: false
  }),
  actions: {
    addDynamicRoutes(routes, parentName = null) {
      routes.forEach(route => {
        if (parentName) {
          router.addRoute(parentName, route)
        } else {
          router.addRoute(route)
        }
        if (route.children && route.children.length > 0) {
          this.addDynamicRoutes(route.children, route.name || route.path)
        }
      })
    },
    setMenuList(list: any[]) {
      this.menuList = list
      this.menuLoaded = true
      // 动态注册路由
      const routes = menuToRoutes(list)
      this.addDynamicRoutes(routes)
      // 注册完动态路由后，强制刷新当前路由（只对动态路由页面且未注册时）
      const currentPath = router.currentRoute.value.fullPath
      if (
        currentPath !== '/' &&
        currentPath !== '/login' &&
        currentPath !== '/dashboard'
      ) {
        if (!router.hasRoute(currentPath)) {
          router.replace(`/redirect${currentPath}`)
        }
      }
    },
    resetMenuList() {
      this.menuList = []
      this.menuLoaded = false
    }
  }
}) 